using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    /// <summary>
    /// 为每个电梯实体创建和保存围栏（一次性），不论电梯实体本身如何创建和销毁，围栏都常驻
    /// 围栏随场景销毁
    /// </summary>
    public class LevelPlayElevatorFenceCtrl : LevelPlaySubBaseCtrl
    {
        private Dictionary<int, GameObject[]> _fenceMap = new();

        protected override void OnModuleGameplayInit()
        {

        }

        protected override void OnSceneLoaded()
        {

        }

        /// <summary>
        /// 初始化围栏
        /// </summary>
        /// <param name="elevator"></param>
        /// <param name="floors"></param>
        /// <returns>围栏数组，注意如果策划没有配置任何围栏会返回null</returns>
        public GameObject[] InitFence(LevelPlayRealityEntity elevator, IReadOnlyList<ElevatorFloorData> floors)
        {
            if (_fenceMap.TryGetValue(elevator.id, out var fences))
            {
                foreach (var fenceGo in fences)
                {
                    fenceGo.SetActive(true);
                }
                return fences;
            }
            for (int i = 0; i < floors.Count; i++)
            {
                var floorData = floors[i];
                var rootTrans = regionCtrl.sceneCtrl.sceneExtraRoot.transform;
                var dynEntity = elevator.GetDynLevelEntity();
                var name = dynEntity.name;
                string goName = $"[{dynEntity.mcid}][{(string.IsNullOrEmpty(name) ? "Null" : name)}]floor_{i}";
                var fenceRoot = LevelPlayUtil.GenElevatorFloorGO(floorData, elevator.transform.rotation, goName);
                if (fenceRoot != null)
                {
                    if (fences == null)
                    {
                        fences = new GameObject[floors.Count];
                        _fenceMap.Add(elevator.id, fences);
                    }
                    fenceRoot.transform.SetParent(rootTrans, false);
                    fences[i] = fenceRoot;
                }
            }
            return fences;
        }

        protected override void OnDispose()
        {
            _fenceMap = null;
        }
    }
}
